﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;
using System.Text.RegularExpressions;
using System.ServiceModel;
using System.Web.Services;

namespace ORS.Metadata
{
    public partial class Metadata : System.Web.UI.Page
    {
        protected string xmldata;

        protected void Page_Load(object sender, EventArgs e)
        {
            xmllist();//加载XML解析文件列表
        }



        /// <summary>
        /// 上传和解析文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            string datafilename = uploadWenjian();  //上传文件的文件名

            string xmlfilename = this.HiddenField1.Value;//获取存放在隐藏控件的XML文件名

            JXwenjian(datafilename, xmlfilename);//解析文件
            //this.ptztxx.Text=
            //保存解析的信息到数据库
        }



        #region  加载XML文件列表
        private void xmllist()
        {
            string[] xmlfile = Directory.GetFiles(Server.MapPath("~/XML"), "*.xml");

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < xmlfile.Length; i++)
            {
                string xmlfilename = Path.GetFileName(xmlfile[i]);//获取文件名

                sb.AppendFormat("<option value=\"{0}\">{1}</option>", xmlfilename, xmlfilename);
            }

            xmldata = sb.ToString();
        }
        #endregion

        #region  上传数据文件，得到数据文件路径
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        private string uploadWenjian()
        {
            try
            {
                if (FileUpload1.PostedFile.FileName == "")
                {
                    Label1.Visible = true;
                    Label1.ForeColor = System.Drawing.Color.FromName("#ff0000");
                    Label1.Text = "请选择数据文件！";
                    return "";
                }
                else
                {
                    //if (FileUpload1.PostedFile.ContentLength > 500000)
                    //{
                    //    Label1.Visible = true;
                    //    Label1.ForeColor = System.Drawing.Color.FromName("#ff0000");
                    //    Label1.Text = "文件过大！";
                    //    return "";
                    //}
                    string datafilepath = FileUpload1.PostedFile.FileName;
                    string filename = datafilepath.Substring(datafilepath.LastIndexOf("."));
                    string dataname = DateTime.Now.ToFileTime() + filename;
                    string serverpath = Server.MapPath("~/dataPic/");
                    if (!Directory.Exists(serverpath))
                    {
                        Directory.CreateDirectory(serverpath);//创建该文件夹
                    }
                    FileUpload1.PostedFile.SaveAs(serverpath + dataname);
                    Label1.Visible = true;
                    Label1.ForeColor = System.Drawing.Color.FromName("#000000");
                    Label1.Text = "上传成功！";

                    return dataname;
                }
            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;
                return "";
            }
        }
        #endregion

        #region 解析数据文件，并放到相应的控件中
        private void JXwenjian(string datafilename, string xmlfilename)
        {
            string xmlfilepath = "~/XML/" + xmlfilename;//解析XML文件的位置
            string datafilepath = "~/dataPic/" + datafilename;//数据文件的位置

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(xmlfilepath));//加载XML文件

            XmlNode root = xmlDoc.SelectSingleNode("file");
            string datatype = root.Attributes["datatype"].Value;//确定图像种类1-8
            string type = root.Attributes["type"].Value;//确定需要解析的是XML类型还是TXT类型


            XmlNode common = root.SelectSingleNode("common");//读取共有属性common节点
            int nodecount = common.ChildNodes.Count;//获取common中node子节点的个数

            string[][] arr = new string[nodecount][];
            int i = 0;
            //Dictionary<string, string> dic = new Dictionary<string, string>();//定义一个字典，用来匹配数据

            #region 读取XML配置文件里的信息  按照一定规制放在arr数组中
            foreach (XmlElement node in common.ChildNodes)
            {
                string structname = node.SelectSingleNode("structname").InnerText;//获取structname中的值，作为查找控件，为控件填充数据
                string filterformat = node.SelectSingleNode("filterformat").InnerText;//获取filterformat中的值，为查找出数据文件中需要读取的数值

                string p1txt = node.ChildNodes[3].InnerText;
                string p1val = node.ChildNodes[3].Attributes["value"].Value;

                string p2txt = node.ChildNodes[4].InnerText;
                string p2val = node.ChildNodes[4].Attributes["value"].Value;

                //string p1txt = node.SelectSingleNode("propertyname").InnerText;
                //XmlNode p1 = node.SelectSingleNode("propertyname");
                //string p1val = p1.Attributes["value"].Value;

                //string p2txt = node.SelectSingleNode("propertyname").InnerText;
                //XmlNode p2 = node.SelectSingleNode("propertyname");
                //string p2val = p2.Attributes["value"].Value;

                arr[i] = new string[] { structname, filterformat, p1txt, p1val, p2txt, p2val };//提取出的信息放到数组里
                i++;
                //dic.Add(structname, filterformat);//把对应关系填充到字典里，建立索引
            }
            #endregion
             Dictionary<string, string> dic  = null;
            if (type.Equals("xml"))//
            {
                //Dictionary<string, string> dic = null;

                XmlDocument dataxml = new XmlDocument();
                dataxml.Load(Server.MapPath(datafilepath));//加载数据文件，XML类型
                XmlNode rootoNode = dataxml.DocumentElement;

                 dic = new Dictionary<string, string>();

                #region 解析数据，放到DIC中
                for (int j = 0; j < arr.Length; j++)
                {
                    string structname = arr[j][0];
                    string filterformat = arr[j][1];

                    string p1txt = arr[j][2];
                    string p1val = arr[j][3];

                    string p2txt = arr[j][4];
                    string p2val = arr[j][5];

                    try
                    {
                        string result =  FitXMLT(rootoNode, filterformat);
                        dic.Add(structname,result);
                    }
                    catch
                    {

                    }

                }
                #endregion

            }
            else if (type.Equals("txt"))
            {
                dic = new Dictionary<string, string>();

                string[] stringlines = File.ReadAllLines(Server.MapPath(datafilepath), Encoding.Default);
                string s1 = string.Empty;
                string s2 = string.Empty;
                string[] data = new string[2];
                foreach (string sline in stringlines)
                {
                    data = sline.Split(':','=');
                    if(data.Length > 1  )
                    {
                        s1 = data[0].Replace(@"""", "");
                        s2 = data[1].Replace(@"""", "");
                        dic.Add(s1.Trim(), s2.Trim());
                    }
                    
               }

            }



            #region 把放到字典里的数据赋值给控件
            if(dic != null)
            {
                foreach (var item in dic)
                {
                    switch (item.Key)
                    {
                        case "PlatformCarrier"://平台载体
                            this.ptztxx.Text = item.Value;
                            break;
                        case "PhotoRegion"://摄区名称
                            this.sqmcxx.Text = item.Value;
                            break;
                        case "Projection"://数学投影
                            this.sxtyxx.Text = item.Value;
                            break;
                        case "ImageFormat"://图像格式
                            this.txgsxx.Text = item.Value;
                            break;
                        case "CoordinateSystem"://坐标系统
                            this.zbxt.Text = item.Value;
                            break;
                        case "SensorName"://传感器名称
                            this.cgqmc.Text = item.Value;
                            break;
                        case "PixlsDepth"://像素位素
                            this.xsws.Text = item.Value;
                            break;
                        case "Scale"://成图比例尺
                            this.ctblc.Text = item.Value;
                            break;
                        case "Resolution"://地面分辨率
                            this.dmfbl.Text = item.Value;
                            break;
                        case "ImgGenDate"://成像日期
                            this.cxrq.Text = item.Value;
                            break;
                        case "imgSize_rows"://图像大小行
                            this.txdxh.Text = item.Value;
                            break;
                        case "TIF"://TIF文件
                            this.TIFwj.Text = item.Value;
                            break;
                        case "ImgGenTime"://成像时间
                            this.cxsj.Text = item.Value;
                            break;
                        case "imgSize_cols"://图像大小列
                            this.txdxl.Text = item.Value;
                            break;
                           
                            
                        default:
                            break;
                    }
                }
            }
              
            #endregion

            else
            {

            }
        }
        #endregion


        #region  遍历所有的节点，找到匹配的节点，返回数据TZQ
        private string FitXMLT(XmlNode farthernode, string filterformat)
        {
            string result = string.Empty;
            if (farthernode.HasChildNodes)
            {
                foreach (XmlNode item in farthernode.ChildNodes)
                {
                    result += FitXMLT(item, filterformat);
                }
            }

            XmlNode filternode = farthernode.SelectSingleNode(filterformat);
            if (filternode != null)
            {
                result += filternode.InnerText;
                return result;
            }
            return result;
        }
        #endregion

        #region  遍历所有的节点，找到匹配的节点，返回数据ZSC
        //private string FitXMLZ(XmlNode farthernode, string filterformat)
        //{
        //    string result = string.Empty;

        //    foreach (XmlNode n1 in farthernode.ChildNodes)
        //    {
        //        if (n1 == farthernode.SelectSingleNode(filterformat))
        //        {
        //            result = n1.InnerText;
        //            break;
        //        }
        //        else if (n1.HasChildNodes)
        //        {
        //            result = FitXMLZ(n1, filterformat);

        //        }
        //        else
        //        {
        //           // FitXMLZ(n1, filterformat);
        //        }

        //    }

        //    return result;
        //}
        #endregion


        #region  保存解析的信息到数据库
        protected void Button2_Click(object sender, EventArgs e)
        {

            //int id = 0;  //ID数，自增长；

            string TYPEID = (101 + 0).ToString();//101-108分别代表8中影像类型

            string TASKID = "00001";//全部默认为00001
            string IMGID = "89C271CF7E39487DB3D4BC98A5A4DA0F";  //暂时

            string DATARESOURCE = "购买";
            string PLATFORMCARRIER = ptztxx.Text;//平台载体

            string SENSORNAME = cgqmc.Text;//传感器名称
            string IMGGENTIME = cxrq.Text;//成像日期时间
            string PHOTOREGION = sqmcxx.Text;//摄区名称
            decimal UPPERLEFTLONG = Convert.ToDecimal(zsjjdxx.Text);//左上角经度
            decimal UPPERLEFTLAT = Convert.ToDecimal(zsjwd.Text);//左上角纬度
            decimal LOWERRIGHTLONG = Convert.ToDecimal(yxjjd.Text);//右下角经度
            decimal LOWERRIGHTLAT = Convert.ToDecimal(yxjwd.Text);//右下角纬度
            decimal SCALE = Convert.ToDecimal(ctblc.Text);//成图比例尺
            decimal RESOLUTION = Convert.ToDecimal(dmfbl.Text);//地面分辨率
            string IMGSIZE = txdxh.Text + "," + txdxl.Text;//图像大小行和列
            decimal PIXLSDEPTH =  Convert.ToDecimal(xsws.Text);//像素位素
            string COORDINATESYSTEM = zbxt.Text;//坐标系统

            string PROJECTION = sxtyxx.Text;//数学投影
            string IMAGEFORMAT = txgsxx.Text;//图像格式
            string PRODUCTLEVEL = cpdj.Text;//产品等级
            string PREVIEWIMG = "";//快视图。本系统不使用
            string IMGFILENAME = "";//图像数据名称
            string IMGFILEPATH = "";//图像数据文件位置
            string IMGDISKINDEX = "";//图像数据文件原始介质（光盘、磁盘等）编号
            string USERID = "Admin";//元数据的输入者
            string METADATADATE = "";//元数据编写日期
            int STATUS = 1;//元数据当前状态，1--可用，0--不可用(删除)
            string REMARK = "";//备注
            string IMGFILESIZE = "";//图像文件大小 





            string ptzt = ptztxx.Text; //平台载体
            string txgs = txgsxx.Text;//图像格式


            ORSIMS.Model.IMAGE_METADATA model = new ORSIMS.Model.IMAGE_METADATA();
            model.ID = 1;
            model.TYPEID = TYPEID;
            model.TASKID = TASKID;
            model.IMGID = IMGID;
            model.DATARESOURCE = DATARESOURCE;
            model.PLATFORMCARRIER = PLATFORMCARRIER;
            model.SENSORNAME = SENSORNAME;
            //model.IMGGENTIME = Convert.ToDateTime("2012/12/12").ToString("hh:mm:ss"); ;
            model.PHOTOREGION = PHOTOREGION;
            model.UPPERLEFTLONG = UPPERLEFTLONG;
            model.UPPERLEFTLAT = UPPERLEFTLAT;
            model.LOWERRIGHTLONG = LOWERRIGHTLONG;
            model.LOWERRIGHTLAT = LOWERRIGHTLAT;
            model.SCALE = SCALE;
            model.RESOLUTION = RESOLUTION;
            model.IMGSIZE = IMGSIZE;
            model.PIXLSDEPTH = PIXLSDEPTH;
            model.COORDINATESYSTEM = COORDINATESYSTEM;
            model.IMAGEFORMAT = IMAGEFORMAT;
            model.PRODUCTLEVEL = PRODUCTLEVEL;
            //model.PREVIEWIMG = "1";
            model.IMGFILENAME = IMGFILENAME;
            model.IMGFILEPATH = IMGFILEPATH;
            model.IMGDISKINDEX = IMGDISKINDEX;
            model.USERID = USERID;
            //model.METADATADATE = METADATADATE;
            model.STATUS = STATUS;
            model.IMGFILESIZE = IMGFILESIZE;

            ORSIMS.BLL.IMAGE_METADATA bll = new ORSIMS.BLL.IMAGE_METADATA();
            bll.Add(model);


        }
        #endregion





    }
}